<template>
  <a-modal :maskClosable="false"
    :title="title"
    :width="drawerWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 85%;overflow-y: hidden">
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model">
        <a-row>
          <a-col span="12">
            <a-form-model-item label="排班科室" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-select v-model="model.systemId" placeholder="请选择排班的科室" @change="loadList">
                <a-select-option v-for="item in departOption" :key="item.key" :value="item.value">{{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col span="12">
            <a-form-model-item label="医生职称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <j-dict-select-tag
                placeholder="请选择职级"
                dictCode="doctor_level"
                v-model="model.title"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col span="12">
            <a-form-model-item label="排班名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input placeholder="请输入排班名称" v-model="model.name" :readOnly="!!model.id" />
            </a-form-model-item>
          </a-col>
          <a-col span="12">
            <a-form-model-item label="班次编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input placeholder="请输入编号" v-model="model.num" :readOnly="!!model.id" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col span="12">
            <a-form-item label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-range-picker v-model="model.date" format="YYYY-MM-DD" />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-model-item label="挂号费用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-select v-model="model.registeredfeeId" placeholder="请选择挂号费用" @change="loadList">
                <a-select-option v-for="item in registeredfeeOptions" :key="item.key" :value="item.value">{{ item.key }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading">
        <a-table-column title="医生名称" data-index="name"></a-table-column>
        <a-table-column :title="column.title" v-for="column in columns" :ellipsis="true">
          <template slot-scope="text, record">
            <template v-for="time in timeOptions">
              <a-checkbox :value="record.id+':'+column.date+':'+column.week+':'+time.value" @change="handleCheck">
                {{ time.text }}
              </a-checkbox>
              <br />
            </template>

          </template>
        </a-table-column>
      </a-table>

    </a-spin>
  </a-modal>
</template>

<script>
import { getAction, httpAction, postAction } from '@/api/manage'
import { queryMyDepartTreeList } from '@api/api'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import moment from 'moment'

export default {
  name: 'DepartEditModal',
  mixins: [JeecgListMixin],
  data() {
    return {
      title: '新增排班计划',
      visible: false,
      loading: false,
      drawerWidth: 900,
      model: {},
      confirmLoading: false,
      departOption: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 查询条件
      queryParam: { 'departId': 0 },
      departId: 0,
      // 表头
      columns: [],
      url: {
        add: '/his/department',
        edit: '/his/department',
        list: '/his/employee/scheduling/list'
      },
      myMap: {},
      startDate: null,
      endDate: null,
      timeOptions: [],
      registeredfeeOptions: [],
      disableMixinCreated:true
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.initRequestData()
    this.myMap = new Map()
  },
  methods: {
    moment,
    initRequestData() {
      let that = this
      queryMyDepartTreeList().then((res) => {
          if (res.success && res.result) {
            that.departOption = res.result
          }
        }
      )
      getAction('sys/dict/getDictItems/his_time_subsection').then((res) => {
        that.timeOptions = res.result
      })

      // getAction('his/registeredfee/all').then((res) => {
      //   that.registeredfeeOptions = res.result
      // })
    },
    convertWeek(value) {
      let getWeek_index = (new Date(value)).getDay()
      const weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      let title = weekArr[getWeek_index] + '(' + value + ')'
      let coloum = { 'title': title, 'week': getWeek_index, 'date': value }
      return coloum
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth
      } else {
        this.drawerWidth = screenWidth - 300
      }
    },
    loadList(val) {
      this.queryParam.departId = val
      this.departId = val
      this.loadData()
    },
    add(startStr, endStr, dayCount) {
      this.startDate = startStr
      this.endDate = endStr
      this.columns = []
      let dateStr = startStr
      for (var i = 0; i < dayCount; i++) {
        dateStr = moment(dateStr).add(i, 'days').format('YYYY-MM-DD')
        this.columns.push(this.convertWeek(dateStr))
      }
      this.resetScreenSize()
      this.model.date = [
        moment(startStr),
        moment(endStr)
      ]
      this.visible = true
    },
    close() {
      this.$refs.form.clearValidate()
      this.$emit('close')
      this.visible = false
    },
    handleCheck(e) {
      let arr = e.target.value.split(':')
      let doctorId = arr[0]
      let date = arr[1]
      let week = arr[2]
      let val = arr[3]
      let list = []
      //需要添加
      if (e.target.checked) {
        if (this.myMap.has(doctorId)) {
          list = this.myMap.get(doctorId)
          list.push({ 'date': date, 'week': week, 'value': val, 'doctorId': doctorId })
          console.log(list)
        } else {
          list = [{ 'date': date, 'week': week, 'value': val, 'doctorId': doctorId }]
        }
      } else {//反选
        var temList = this.myMap.get(doctorId)
        for (var i = 0; i < temList.length; i++) {
          let obj = temList[i]
          if (obj.title === title && obj.value === val) {
            console.log('相等')
          } else {
            list.push(obj)
          }
        }
      }
      this.myMap.set(doctorId, list)
    },
    handleOk() {
      const that = this
      let list = []
      let hasData = false
      this.myMap.forEach(function(value, key, set) {
        value.forEach(function(item, index) {
            list.push(item)
            hasData = true
          }
        )
      })
      if (!hasData) {
        this.$message.warn('请为医生进行排班计划')
        return
      }
      httpAction('/his/scheduling', {
        'departId': this.departId,
        'startDate': this.startDate,
        'endDate': this.endDate,
        'registeredfeeId':this.model.registeredfeeId,
        'data': list
      }, 'post').then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.close()
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.confirmLoading = false
        that.close()
      })

      // const that = this
      // // 触发表单验证
      // this.$refs.form.validate(valid => {
      //   if (valid) {
      //     that.confirmLoading = true
      //     let url = this.url.add
      //     let method = 'post'
      //     if (this.model.did) {
      //       url = this.url.edit
      //       method = 'put'
      //     }
      //
      //   } else {
      //     return false
      //   }
      // })
    },
    handleCancel() {
      this.close()
    },
    validateRoleCode(rule, value, callback) {
      if (/[\u4E00-\u9FA5]/g.test(value)) {
        callback('科室编号不可输入汉字!')
      } else {
        let params = {
          tableName: 'sys_role',
          fieldName: 'role_code',
          fieldVal: value,
          dataId: this.model.id
        }
        // duplicateCheck(params).then((res)=>{
        //   if(res.success){
        //     callback();
        //   }else{
        //     callback(res.message);
        //   }
        // });
      }
    }
  }
}
</script>

<style scoped>

</style>